package com.whsxt.realm;


import com.whsxt.common.Constants;
import com.whsxt.domain.Permission;
import com.whsxt.domain.Role;
import com.whsxt.domain.User;
import com.whsxt.service.PermissionService;
import com.whsxt.service.RoleService;
import com.whsxt.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.*;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;
    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取token信息里的用户名信息
        String username = authenticationToken.getPrincipal().toString();
        User user = userService.loadUserByUsername(username);
        if(null == user){
            return null;
        }

        if(user.getDeleted() == 0){
            throw new AuthenticationException("该用户已被禁用");
        }

        // 执行到此处则证明用户存在
        // 将查出来的用户赋予给activeUser
        ActiveUser activeUser = new ActiveUser();
        activeUser.setUser(user);

        // 先通过 登录的用户ID查询出所有拥有按钮的权限
        List<Permission> perms = permissionService.selectPermsByUserId(activeUser.getUser().getId(), Arrays.asList(2));
        List<Role> roles = roleService.selectRolesByUserId(activeUser.getUser().getId());

        // 将权限放入 ActiveUser
        activeUser.setPerms(getPermsSet(perms));
        activeUser.setRoles(getRolesSet(roles));

        return new SimpleAuthenticationInfo(activeUser, user.getLoginPassword(), ByteSource.Util.bytes(Constants.DEFAULT_SALT), user.getRealname());
    }

    /**
     * 将角色的集合转化为角色的set集合
     * @param roles
     * @return
     */
    private Set<String> getRolesSet(List<Role> roles) {
        if(CollectionUtils.isEmpty(roles)){
            return Collections.emptySet();
        }

        Set<String> rolesSet = new HashSet<>();
        for (Role role : roles) {
            rolesSet.add(role.getTag());
        }
       return rolesSet;
    }

    /**
     * 用权限数据List集合转化为set集合
     * @param perms
     * @return
     */
    private Set<String> getPermsSet(List<Permission> perms) {

        if(CollectionUtils.isEmpty(perms)){
            return Collections.emptySet();
        }

        Set<String> permSet = new HashSet<>();

        for (Permission perm : perms) {
            permSet.add(perm.getTag());
        }
        return permSet;
    }


    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 获取ActiveUser对象
        ActiveUser activeUser = (ActiveUser) principalCollection.getPrimaryPrincipal();
        // 设置角色与权限
        simpleAuthorizationInfo.setStringPermissions(activeUser.getPerms());
        simpleAuthorizationInfo.setRoles(activeUser.getRoles());

        return simpleAuthorizationInfo;
    }


}
